import { defineStore } from 'pinia'
import type { MenuItem, MenuRoute } from '@/types/store'
import { getMenus } from '@/api'

const id = 'menu'
const initMenuActive = 'home'
const initMenuItem: MenuItem = {
  name: initMenuActive,
  icon: 'House',
  title: '控制台',
  full: false,
  children: []
}

const store = defineStore(id, {
  state: () => ({
    collapse: false,
    menus: [initMenuItem] as MenuItem[],
    menuActive: initMenuActive,
    menuRoutes: [] as MenuRoute[]
  }),
  getters: {},
  actions: {
    async refresh(access: Record<string, boolean>) {
      const menus = await getMenus()
      const delMenus: Array<[MenuItem[], number]> = []
      this.menuRoutes = []

      const recursion = (menus: MenuItem[]) => {
        menus.forEach((menu, i) => {
          if (typeof menu.permission === 'undefined' || access[menu.permission]) {
            this.menuRoutes.push({ name: menu.name, full: menu.full })
            if (menu.children.length > 0) {
              recursion(menu.children)
            }
          } else {
            delMenus.push([menus, i])
          }
        })
      }
      recursion(menus)
      delMenus.sort((a, b) => b[1] - a[1]).forEach(([a, i]) => a.splice(i, 1))
      this.menus = [initMenuItem, ...menus]
    }
  },
  persist: {
    key: id
    // 需要持久化存储的 key
    // paths: ['token', 'user', 'menuActive', 'tabs', 'layout', 'collapse']
  }
})

export default store
